package com.xq.tmall.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xq.tmall.controller.BaseController;
import com.xq.tmall.entity.*;
import com.xq.tmall.service.*;
import com.xq.tmall.util.OrderUtil;
import com.xq.tmall.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@Controller
public class NoticeController extends BaseController {

    @Resource(name = "noticeService")
    private NoticeService noticeService;

    @Resource(name = "productService")
    private ProductService productService;


    //转到后台管理-公告页-ajax
    @RequestMapping(value = "admin/notice", method = RequestMethod.GET)
    public String goToPage(HttpSession session, Map<String, Object> map) {
        logger.info("获取前10条公告列表");
        PageUtil pageUtil = new PageUtil(0, 10);
        List<Notice> noticeList = noticeService.getList(null, pageUtil);
        map.put("noticeList", noticeList);
        logger.info("获取公告总数量");
        Integer noticeTotal = noticeService.getTotal(null);
        map.put("noticeTotal", noticeTotal);
        logger.info("获取分页信息");
        pageUtil.setTotal(noticeTotal);
        map.put("pageUtil", pageUtil);
        logger.info("转到后台管理-分类页-ajax方式");
        return "admin/noticeManagePage";
    }

    //转到后台管理-公告详情页-ajax
    @RequestMapping(value = "admin/notice/{cid}", method = RequestMethod.GET)
    public String goToDetailsPage(HttpSession session, Map<String, Object> map, @PathVariable Integer cid/* 分类ID */) {
        logger.info("获取notice_id为{}的id", cid);
        Notice notice = noticeService.queryById(cid);
        map.put("notice", notice);
        if (notice.getNoticeContent() != null) {
            String substring = notice.getNoticeContent().substring(notice.getNoticeContent().lastIndexOf("/") + 1);
            logger.info("获取产品为{}的id", substring);
            Product product = productService.get(Integer.parseInt(substring));
            List<Product> productList = new ArrayList<>();
            productList.add(product);
            map.put("productList", productList);
        }
        logger.info("转到后台管理-公告详情页-ajax方式");
        return "admin/include/noticeDetails";
    }

    //转到后台管理-产品类型添加页-ajax
    @RequestMapping(value = "admin/notice/new", method = RequestMethod.GET)
    public String goToAddPage(HttpSession session, Map<String, Object> map) {
        PageUtil pageUtil = new PageUtil(0, 5);
        List<Product> productList = productService.getList(null, new Byte[]{2}, null, pageUtil);
        map.put("productList", productList);
        logger.info("获取产品总数量");
        Integer productCount = productService.getTotal(null,  new Byte[]{2});
        map.put("productCount", productCount);
        logger.info("获取分页信息");
        pageUtil.setTotal(productCount);
        map.put("pageUtil", pageUtil);
        return "admin/include/noticeDetails";
    }

    //按条件查询产品-ajax
    @ResponseBody
    @RequestMapping(value = "admin/notice/new/{index}/{count}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String getProductBySearch(@PathVariable Integer index/* 页数 */,
                                     @PathVariable Integer count/* 行数 */) throws UnsupportedEncodingException {
        JSONObject object = new JSONObject();
        logger.info("按条件获取第{}页的{}条产品", index + 1, count);
        PageUtil pageUtil = new PageUtil(index, count);
        List<Product> productList = productService.getList(null, new Byte[]{2}, null, pageUtil);
        object.put("productList", JSONArray.parseArray(JSON.toJSONString(productList)));
        logger.info("按条件获取产品总数量");
        Integer productCount = productService.getTotal(null, new Byte[]{2});
        object.put("productCount", productCount);
        logger.info("获取分页信息");
        pageUtil.setTotal(productCount);
        object.put("totalPage", pageUtil.getTotalPage());
        object.put("pageUtil", pageUtil);
        logger.info("数据" + JSON.toJSONString(object));
        return object.toJSONString();
    }


    //添加产品类型信息-ajax
    @ResponseBody
    @RequestMapping(value = "admin/addNotice", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String addNotice(@RequestParam String noticeTitle , @RequestParam String shop_id) {
//        String noticeTitle = String.valueOf(map.get("noticeTitle"));
//        String shop_id = String.valueOf(map.get("shop_id"));
        JSONObject jsonObject = new JSONObject();
        logger.info("整合公告信息");
        Notice notice = new Notice();
        notice.setNoticeDate(new Date());
        notice.setNoticeTitle(noticeTitle);
        notice.setNoticeContent("http://localhost:8080/tmall/product/" + shop_id);
        logger.info("添加公告信息");
        Integer insert = noticeService.insert(notice);
        if (insert != null) {
            logger.info("添加成功！,新增公告的ID值为：{}", insert);
            jsonObject.put("success", true);
            jsonObject.put("noticeId", insert);
        } else {
            jsonObject.put("success", false);
            logger.warn("添加失败！事务回滚");
            throw new RuntimeException();
        }
        return jsonObject.toJSONString();
    }

    //更新产品类型信息-ajax
    @ResponseBody
    @RequestMapping(value = "admin/notice/{noticeId}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public String updateNotice(@RequestParam String noticeTitle/* 公告标题 */,
                               @RequestParam String shop_id/* 商品Id */,
                               @PathVariable("noticeId") Integer noticeId/* 分类ID */) {
        JSONObject jsonObject = new JSONObject();
        logger.info("整合公告");
        Notice notice = new Notice();
        notice.setNoticeDate(new Date());
        notice.setNoticeTitle(noticeTitle);
        logger.info("更新分类信息，分类ID值为：{}", noticeId);
        notice.setNoticeContent("http://localhost:8080/tmall/product/" + shop_id);
        boolean yn = noticeService.update(notice);
        if (yn) {
            logger.info("更新成功！");
            jsonObject.put("success", true);
            jsonObject.put("noticeId", noticeId);
        } else {
            jsonObject.put("success", false);
            logger.info("更新失败！事务回滚");
            throw new RuntimeException();
        }
        return jsonObject.toJSONString();
    }

    //按条件查询产品类型-ajax
    @ResponseBody
    @RequestMapping(value = "admin/notice/{index}/{count}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String getnoticeBySearch(@RequestParam(required = false) String noticeTitle/* 分类名称 */,
                                    @PathVariable Integer index/* 页数 */,
                                    @PathVariable Integer count/* 行数 */) throws UnsupportedEncodingException {
        //移除不必要条件
        if (noticeTitle != null) {
            //如果为非空字符串则解决中文乱码：URLDecoder.decode(String,"UTF-8");
            noticeTitle = "".equals(noticeTitle) ? null : URLDecoder.decode(noticeTitle, "UTF-8");
        }
        JSONObject object = new JSONObject();
        logger.info("按条件获取第{}页的{}条分类", index + 1, count);
        PageUtil pageUtil = new PageUtil(index, count);
        List<Notice> noticeList = noticeService.getList(noticeTitle, pageUtil);
        object.put("noticeList", JSONArray.parseArray(JSON.toJSONString(noticeList)));
        logger.info("按条件获取公告总数量");
        Integer noticeServiceTotal = noticeService.getTotal(noticeTitle);
        object.put("noticeServiceTotal", noticeServiceTotal);
        logger.info("获取分页信息");
        pageUtil.setTotal(noticeServiceTotal);
        object.put("totalPage", pageUtil.getTotalPage());
        object.put("pageUtil", pageUtil);
        return object.toJSONString();
    }
}
